<template>
  <Charts ref="charts" style="height: 400px;" :option="option" />
</template>

<script>
import { ref, watch } from 'vue'
import app from '@/app'
import model from '../model'
import Charts from '@/components/charts'

export default {
  components: {
    Charts
  },
  props: ['name'],
  setup(props) {
    const plugin = app.plugin.index
    const charts = ref()

    // 时间轴
    const time = model.time
    // 数据
    const data = model.data
    // 列表
    const list = model.list

    // 图表
    const buildChartsData = {
      count: () => buildCharts([
        {
          name: plugin.lang('order.count'),
          type: 'line',
          smooth: true,
          areaStyle: {},
          data: list.count.value
        }
      ]),
      total: () => buildCharts([
        {
          name: plugin.lang('order.total'),
          type: 'line',
          smooth: true,
          areaStyle: {},
          data: list.total.value
        },
      ], true),
      tax: () => buildCharts([
        {
          name: plugin.lang('order.tax_req'),
          type: 'line',
          smooth: true,
          stack: 'tax',
          areaStyle: {},
          emphasis: {
            focus: 'series'
          },
          data: list.req.value
        },
        {
          name: plugin.lang('order.tax_tax'),
          type: 'line',
          smooth: true,
          stack: 'tax',
          areaStyle: {},
          emphasis: {
            focus: 'series'
          },
          data: list.tax.value
        },
      ], true),
      profit: () => buildCharts([
        {
          name: plugin.lang('order.profit'),
          type: 'line',
          smooth: true,
          areaStyle: {},
          data: list.profit.value
        }
      ], true)
    }

    // 图表框架
    const buildCharts = (series, money = false) => {
      const data = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          bottom: 'bottom'
        },
        xAxis: {
          type: 'category',
          data: time.value
        },
        yAxis: {
          type: 'value',
          axisLabel: {}
        },
        grid: {
          left: 20,
          right: 20,
          top: 20,
          bottom: 40,
          containLabel: true
        },
        series
      }

      if(money) {
        data.tooltip.valueFormatter = value => app.money(value)
        data.yAxis.axisLabel.formatter = value => app.money(value)
      }
      
      option.value = data
    }

    const option = ref({})

    // 切换图表
    watch(() => props.name, () => {
      charts.value.clear()
      buildChartsData[props.name]()
    })

    // 图表更新
    watch(time, () => {
      buildChartsData[props.name]()
    }, { deep: true })

    // 首次加载
    buildChartsData[props.name]()

    return {
      money: app.money,
      plugin,
      data,
      charts,
      option,
    }
  }
}
</script>